import { mapState, mapMutations } from 'vuex'
import {
  getPhone,
  update,
  setUserInfo,
  getUserInfo,
  getPhoneByAli,
  loginByAli,
  getAliUserInfo,
  updateAliUser
} from '@/api'
export default {
  methods: {
    ...mapMutations(['setUserInfo']),
    getUserPhone(e) {
      //#ifdef MP-WEIXIN
      const { iv, encryptedData } = e.detail
      wx.login({
        success: res => {
          getPhone(res.code, iv, encryptedData).then(response => {
            if (response.data) {
              update({ openid: this.openId, phone: response.data }).then(
                res => {
                  this.setUserInfo(res.data)
                  this.checks()
                }
              )
            }
          })
        }
      })
      //#endif
      //#ifdef MP-ALIPAY
      my.getPhoneNumber({
        success: res => {
          let encryptedData = res.response
          getPhoneByAli(JSON.parse(encryptedData)).then(response => {
            updateAliUser({
              zfbId: this.userInfo.zfbId,
              phone: response.mobile
            }).then(res => {
              this.setUserInfo(res.data)
            })
          })
        },
        fail: res => {
          console.log(res)
        }
      })
      //#endif
    },
    // 登录获取用户名，不包含手机号
    login() {
      //#ifdef MP-WEIXIN
      wx.getUserProfile({
        desc: '用于完善会员资料',
        success: result => {
          const { avatarUrl, nickName } = result.userInfo
          setUserInfo(this.openId, avatarUrl, nickName).then(res => {
            getUserInfo(this.openId).then(res => {
              this.setUserInfo(res.data)
            })
          })
        }
      })
      //#endif
      //#ifdef MP-ALIPAY
      my.getAuthCode({
        scopes: 'auth_user',
        success: res => {
          getAliUserInfo(res.authCode).then(result => {
            const { phone, zfbId, memberName, headimg } = result
            loginByAli(phone, zfbId, headimg, memberName).then(response => {
              this.setUserInfo(response.data)
            })
          })
        }
      })
      //#endif
    },
    back() {
      uni.navigateBack()
    },
    changeRules(index) {
      this.showRules = !this.showRules
      this.current = index
    }
  },
  computed: {
    ...mapState(['userInfo', 'openId'])
  }
}
